<?php

namespace app\admin\logic\Order;

use app\admin\model\WholesalOrderItem;

class WholesalAssets
{
    /**
     * 释放经销商资产
     * @param array $orderItems 订单商品数组
     * @return array
     * @throws \Exception
     */
    public function releaseAssets($orderItems)
    {
        try {
            if (count($orderItems) == 0) {
                throw new \Exception('订单商品不存在');
            }

            $wholesal_id = reset($orderItems)['wholesal_id'];

            foreach ($orderItems as $item) {
                $wholesalWhere = [
                    'order_id' => $wholesal_id,
                    'product_id' => $item['product_id'],
                    'warehouse_id' => $item['warehouse_id'],
                    'arrival_date' => $item['arrival_date'],
                    'is_futures' => $item['is_futures']
                ];

                $oWholesalOrderItem = WholesalOrderItem::where($wholesalWhere)->select();
                if (!$oWholesalOrderItem) {
                    throw new \Exception('订单商品不存在');
                }

                $total_qty = $oWholesalOrderItem[0]->quantity;
                if ($total_qty < $item['pending_quantity']) {
                    throw new \Exception('订单商品数量不足');
                }

                $surplus = 0; // 剩余数量
                foreach ($oWholesalOrderItem as $val) {
                    $quantity = $surplus == 0 ? $item['pending_quantity'] : $surplus;
                    if ($val->lock_qty >= $quantity) {
                        $val->lock_qty = $val->lock_qty - $item['pending_quantity'];
                        $surplus = 0;
                    } elseif ($val->lock_qty < $item['pending_quantity']) {
                        $val->lock_qty = 0;
                        $surplus = $item['pending_quantity'] - $val->lock_qty;
                    }
                    $val->save();
                }
            }

            return ['code' => 0, 'message' => 'success'];
        } catch (\Exception $e) {
            return ['code' => 1, 'message' => $e->getMessage()];
        }
    }
}
